﻿namespace MicroCloud.Api.Identity.Areas.Admin.Controllers.Identity
{
    /// <summary>
    /// 管理-登录日志
    /// </summary>
    [Description("管理-登录日志")]
    [ModuleInfo(Code = "LoginLog", Name = "登录日志", OrderNo = 7, Position = "Identity", PositionName = "认证模块")]
    public class LoginLogController : AdminControllerBase
    {
        #region 属性
        /// <summary>
        /// 获取 身份认证业务契约
        /// </summary>
        protected IIdentityContract IdentityContract => ServiceProvider.GetService<IIdentityContract>();

        #endregion

        #region Action方法
        /// <summary>
        /// 读取
        /// </summary>
        /// <param name="request">分页请求</param>
        /// <returns>登录日志页列表</returns>
        [HttpPost]
        [ModuleInfo]
        [Description("读取")]
        public virtual PageData<LoginLogOutputDto> Read(PageRequest request)
        {
            Check.NotNull(request, nameof(request));

            IFunction function = this.GetExecuteFunction();
            Expression<Func<LoginLog, bool>> predicate = FilterService.GetExpression<LoginLog>(request.FilterGroup);
            request.AddDefaultSortCondition(new SortCondition("CreatedTime", ListSortDirection.Descending));

            var page = CacheService.ToPageCache(IdentityContract.LoginLogs, predicate, request.PageCondition,
                 m => new
                 {
                     D = m,
                     User = new { m.User.UserName, m.User.NickName }
                 }
                , function).ToPageResult(data => data.Select(m => new LoginLogOutputDto(m.D)
                {
                    UserName = m.User.UserName,
                    UserNickname = m.User.NickName
                }).ToArray()); ;
            return page.ToPageData();

            //var page = IdentityContract.LoginLogs.ToPage(predicate,
            //    request.PageCondition,
            //    m => new
            //    {
            //        D = m,
            //        User = new { m.User.UserName, m.User.NickName }
            //    }).ToPageResult(data => data.Select(m => new LoginLogOutputDto(m.D)
            //    {
            //        UserName = m.User.UserName,
            //        UserNickname = m.User.NickName
            //    }).ToArray());

            //return page.ToPageData();
        }

        /// <summary>
        /// 删除登录日志
        /// </summary>
        /// <param name="ids">登录日志编号</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        [ModuleInfo]
        [DependOnFunction(nameof(Read))]
        [UnitOfWork]
        [Description("删除")]
        public virtual async Task<AjaxResult> Delete(params long[] ids)
        {
            Check.NotNull(ids, nameof(ids));

            OperationResult result = await IdentityContract.DeleteLoginLogs(ids);
            return result.ToAjaxResult();
        }

        #endregion

    }

}
